<script setup lang="ts">
import { ref, computed } from "vue";
import { useColumns } from "./columns";
import "plus-pro-components/es/components/search/style/css";
import {
  PlusSearch,
  PlusDialogForm,
  type PlusColumn,
  type FieldValues
} from "plus-pro-components";
import { ElMessage, ElMessageBox } from "element-plus";
import { router } from "@/router";
import dialogForms, { type FormProps } from "./handle.vue";
import { setUser, doPartner, cancelPartner } from "@/api/user";

import { addDialog } from "@/components/ReDialog";
defineOptions({
  name: "UserHhr"
});
import { useMenu } from "@/utils/power";
const power = useMenu(["info", "pubRed"]);

const searchColumns: PlusColumn[] = [
  {
    label: "搜索",
    width: 200,
    prop: "keyWord",
    valueType: "copy",
    tooltip: "请输入搜索关键词"
  },
  {
    label: "查询用户下级",
    width: 100,
    labelWidth: 120,
    prop: "pId",
    fieldProps: {
      controls: false
    },
    valueType: "input-number",
    tooltip: "请输入用户ID"
  },
  {
    label: "是否等级固定",
    prop: "levelAdmin",
    labelWidth: 120,
    valueType: "select",
    options: [
      {
        label: "否",
        value: 0,
        color: "red"
      },
      {
        label: "是",
        value: 1,
        color: "red"
      }
    ]
  },
  {
    label: "等级",
    prop: "level",
    valueType: "select",
    options: [
      {
        label: "普通用户",
        value: 0
      },
      {
        label: "VIP1",
        value: 1
      },
      {
        label: "VIP2",
        value: 2
      },
      {
        label: "VIP3",
        value: 3
      },
      {
        label: "VIP4",
        value: 4
      },
      {
        label: "VIP5",
        value: 5
      },
      {
        label: "VIP6",
        value: 6
      },
      {
        label: "VIP7",
        value: 7
      }
    ]
  },
  {
    label: "用户状态",
    prop: "status",
    valueType: "select",
    options: [
      {
        label: "启用",
        value: "normal"
      },
      {
        label: "禁用",
        value: "hidden"
      }
    ]
  },
  {
    label: "权重值",
    width: 200,
    prop: "weight",
    valueType: "input-number",
    tooltip: "请输入大于权重值的订单"
  }
];

const searchValues = ref({ starrating: 1 });
const defaultSearchState = ref({ starrating: 1 });

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  onSizeChange,
  loadData,
  onKeywordChange,
  onCurrentChange
} = useColumns();
const columnsRef = computed(() => {
  if (power.value.info) {
    return columns;
  }
  const columnsCopy = [...columns];
  return columnsCopy.slice(0, -1);
});
function detailClick(row) {
  console.log(
    "%crow===详情>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  router.push({ name: "UserDetail", query: { id: row.id } });
}

const rules = {};
const formColumns: PlusColumn[] = [
  {
    label: "余额",
    prop: "money",
    valueType: "input"
  },
  {
    label: "收益",
    prop: "score",
    valueType: "input"
  },
  {
    label: "等级",
    prop: "level",
    valueType: "select",
    options: [
      {
        label: "普通用户",
        value: 0
      },
      {
        label: "VIP1",
        value: 1
      },
      {
        label: "VIP2",
        value: 2
      },
      {
        label: "VIP3",
        value: 3
      },
      {
        label: "VIP4",
        value: 4
      },
      {
        label: "VIP5",
        value: 5
      },
      {
        label: "VIP6",
        value: 6
      },
      {
        label: "VIP7",
        value: 7
      }
    ]
  },
  {
    label: "显示等级",
    prop: "showLevel",
    valueType: "select",
    options: [
      {
        label: "普通用户",
        value: 0
      },
      {
        label: "VIP1",
        value: 1
      },
      {
        label: "VIP2",
        value: 2
      },
      {
        label: "VIP3",
        value: 3
      },
      {
        label: "VIP4",
        value: 4
      },
      {
        label: "VIP5",
        value: 5
      },
      {
        label: "VIP6",
        value: 6
      },
      {
        label: "VIP7",
        value: 7
      }
    ]
  },
  {
    label: "是否合伙人",
    prop: "starrating",
    valueType: "select",
    options: [
      {
        label: "普通用户",
        value: 0
      },
      {
        label: "合伙人",
        value: 1
      }
    ]
  },
  {
    label: "是否固定等级",
    prop: "levelAdmin",
    valueType: "select",
    options: [
      {
        label: "不固定",
        value: "0"
      },
      {
        label: "固定",
        value: "1"
      }
    ]
  },
  {
    label: "用户状态",
    prop: "status",
    valueType: "select",
    options: [
      {
        label: "启用",
        value: "normal"
      },
      {
        label: "禁用",
        value: "hidden"
      }
    ]
  },
  {
    label: "静态释放",
    prop: "jtsfkg",
    valueType: "select",
    options: [
      {
        label: "关闭",
        value: 0
      },
      {
        label: "开启",
        value: 1
      }
    ]
  }
];
const visible = ref(false);
const values = ref<FieldValues>({});
const confirmLoading = ref(false);
function editClick(row) {
  console.log(
    "%crow===编辑>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  values.value = {
    userId: row.id,
    money: row.money,
    score: row.score,
    level: row.level,
    starrating: row.starrating,
    status: row.status,
    showLevel: row.showLevel,
    levelAdmin: row.level_admin,
    jtsfkg: row.jtsfkg
  };
  visible.value = true;
}

const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...values.value };
  console.log("updatedValues", updatedValues);

  confirmLoading.value = true;
  try {
    const res = await setUser(updatedValues);
    visible.value = false;
    confirmLoading.value = false;
    formRef.value?.formInstance?.resetFields();
    ElMessage.success("编辑成功");
    loadData();
  } catch (error) {
    confirmLoading.value = false;
    console.log(error, "error");
  }
};

const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset");
  onKeywordChange(value);
};

const handleChange = (value: any, target: any) => {
  console.log("change", value);
  if (
    target.prop == "keyWord" ||
    target.prop == "pId" ||
    target.prop == "weight"
  ) {
    return;
  }
  onKeywordChange(value);
};

const fullscreenLoading = ref(false);
const doFenhong = async (hhrAmount: number, done: Function) => {
  fullscreenLoading.value = true;
  try {
    const res = await doPartner(hhrAmount);
    ElMessage.success(res.data);
  } catch (error) {
    console.log(error, "error");
  }
  fullscreenLoading.value = false;
  done();
};

const showFenhongDialog = () => {
  addDialog({
    title: "输入发放分红金额",
    width: "30%",
    draggable: true,
    sureBtnLoading: true,
    popconfirm: {
      title: "确定发放分红吗？"
    },
    contentRenderer: () => dialogForms,
    props: {
      formInline: {
        hhrAmount: 0
      }
    },
    beforeSure: (done, { options, index }) => {
      const { formInline } = options.props;
      console.log("options", formInline);
      const hhrAmount = formInline.hhrAmount;
      doFenhong(hhrAmount, done);
    }
  });
};
const formRef = ref();

const cancelFenhongDialog = () => {
  ElMessageBox.prompt("输入取消分红的处理ID", "取消分红", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    showInput: true,
    inputType: "number"
  })
    .then(async ({ value }) => {
      if (!value || value === 0) {
        ElMessage.error("请输入处理ID");
        return;
      }
      ElMessageBox.prompt(`您确定取消 ${value} 分红吗?`, "取消分红", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showInput: false,
        type: "warning"
      })
        .then(async () => {
          try {
            await cancelPartner(value);
            ElMessage.success("取消分红成功");
          } catch (error) {
            console.log(error, "error");
          }
        })
        .catch(() => {});
    })
    .catch(() => {});
};
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>合伙人</h3>
        </template>
        <template v-if="power.pubRed" #extra>
          <el-button
            v-loading.fullscreen.lock="fullscreenLoading"
            type="primary"
            size="default"
            class="mb-4!"
            @click="showFenhongDialog"
          >
            发放分红
          </el-button>
          <el-button
            v-loading.fullscreen.lock="fullscreenLoading"
            type="danger"
            size="default"
            class="mb-4!"
            @click="cancelFenhongDialog"
          >
            取消分红
          </el-button>
        </template>
        <PlusSearch
          v-model="searchValues"
          :defaultValues="defaultSearchState"
          class="mt-5"
          :columns="searchColumns"
          :hasUnfold="false"
          @reset="handleReset"
          @search="handleSearch"
          @change="handleChange"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      :adaptive="false"
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columnsRef"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #operation="{ row }">
        <el-button
          v-if="power.info"
          type="info"
          size="small"
          @click="detailClick(row)"
        >
          详情
        </el-button>
        <el-button
          v-if="false"
          type="primary"
          size="small"
          @click="editClick(row)"
          >编辑</el-button
        >
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading }"
      title="编辑用户信息"
      @confirm="handleSubmit"
    />
  </ElCard>
</template>

<style scoped></style>
